<template>
  <div class="relative w-full h-full">
    <PageHeader :title="$t('settlementBill.index.结算账单')" />
    <SearchCom
      :searchList="searchList"
      @search="handleSearch"
      @reset="handleReset"
      ref="searchComRef"
    />

    <div class="mt12 toolbar flex_aic_jcsb">
      <div class="addBtn flex_aic_jcc" @click="handleExport" v-loading="exportLoading">
        <SvgIcon name="iconziyuan23" class="mr8" color="rgb(24, 144, 255)" />
        <span>{{ $t('settlementBill.index.结算单导出') }}</span>
      </div>
    </div>
    <el-table
      :data="tableData"
      style="width: 100%"
      class="cover-table mt20"
      height="calc(100% - 250px)"
      border
      v-loading="loading"
    >
      <el-table-column type="index" :label="$t('settlementBill.index.序号')" width="200" />
      <el-table-column
        :prop="['tenantName' + locale]"
        :label="$t('settlementBill.index.店铺名称')"
        width="200"
      />
      <el-table-column prop="billCode" :label="$t('settlementBill.index.结算单号')" width="200" />
      <el-table-column prop="createdTime" :label="$t('settlementBill.index.出账时间')" width="200">
        <template #default="scope">
          {{ moment(scope.row.createdTime).format("YYYY-MM-DD HH:mm:ss") }}
        </template>
      </el-table-column>
      <el-table-column prop="finishTime" :label="$t('settlementBill.index.结算日')" width="200">
        <template #default="scope">
          {{scope.row.finishTime !== null ? moment(scope.row.finishTime).format("YYYY-MM-DD HH:mm:ss") : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="payReal" :label="$t('settlementBill.index.订单实付金额') + `(${$t('currency.元')})`" width="180"/>
      <el-table-column prop="commissionTotal" :label="$t('settlementBill.index.佣金') + `(${$t('currency.元')})`" width="200" />
      <el-table-column prop="refundReal" :label="$t('settlementBill.index.退款金额') + `(${$t('currency.元')})`" width="200" />
      <el-table-column
        prop="payDiscountPoint"
        :label="$t('settlementBill.index.积分抵扣金额')"
        width="200"
      />
      <el-table-column
        prop="commissionIncomeTotal"
        :label="$t('settlementBill.index.结算金额') + `(${$t('currency.元')})`"
        width="200"
      />
      <el-table-column prop="status" :label="$t('settlementBill.index.结算状态')" width="160">
        <template #default="scope">
          <el-tag :type="statusMap[scope.row.status]?.type">
            {{ statusMap[scope.row.status]?.label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('settlementBill.index.操作')" width="140" fixed="right">
        <template #default="scope">
          <el-button type="text" @click="handleView(scope.row)">{{ $t('settlementBill.index.查看') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="flex justify-end mt24 absolute bottom-0 right-0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import Api from "@/config/api/api";
import { useI18n } from "vue-i18n";
import moment from "moment";
import SearchCom from "@/components/SearchCom.vue";
import FileSaver from "file-saver";

const { locale, t: $t } = useI18n();

const searchComRef = ref(null);

const searchList = [
  {
    label: $t('settlementBill.index.店铺名称'),
    key: "tenantName",
    type: "input",
  },
  {
    label: $t('settlementBill.index.结算单号'),
    key: "billCode",
    type: "input",
  },
  {
    label: $t('settlementBill.index.出账时间'),
    key: "date",
    type: "daterange",
    dateType: "datetimerange",
  },
  {
    label: $t('settlementBill.index.结算状态'),
    key: "status",
    type: "select",
    options: [
      {
        label: $t('settlementBill.index.待平台审核'),
        value: 1,
      },
      {
        label: $t('settlementBill.index.待打款'),
        value: 2,
      },
      {
        label: $t('settlementBill.index.驳回'),
        value: -1,
      },
      {
        label: $t('settlementBill.index.已打款'),
        value: 3,
      },
    ],
  },
];

const router = useRouter();

const exportLoading = ref(false);
const statusOptions = [
  { label: $t('settlementBill.index.待审核'), value: 1, type: "primary" },
  { label: $t('settlementBill.index.待打款'), value: 2, type: "warning" },
  { label: $t('settlementBill.index.已打款'), value: 3, type: "success" },
  { label: $t('settlementBill.index.驳回'), value: -1, type: "danger" },
];

const statusMap = {};
statusOptions.forEach((el) => {
  statusMap[el.value] = el;
});

const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(100);
const loading = ref(false);

const tableData = ref([]);

const handleSearch = (params) => {
  currentPage.value = 1;
  getDataList(params);
};

const handleReset = () => {
  currentPage.value = 1;
  getDataList();
};

const handleView = (row) => {
  console.log("查看详情：", row);
  router.push({
    path: "/manage_product/settlementBill/detail",
    query: {
      id: row.id,
    },
  });
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  getDataList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getDataList();
};

const handleExport = () => {
  if (exportLoading.value) return;
  exportLoading.value = true;
  const { billCode, date, status, tenantName } =
    searchComRef.value.getFormData();
  const params = {
    billCode,
    status,
    ["tenantName" + locale.value]: tenantName,
    createdTimeStart: date?.[0]
      ? moment(date?.[0]).format("YYYY-MM-DD HH:mm:ss")
      : undefined,
    createdTimeEnd: date?.[1]
      ? moment(date?.[1]).format("YYYY-MM-DD HH:mm:ss")
      : undefined,
  };
  Api.exportTenantSettlement(params)
    .then((res) => {
      FileSaver.saveAs(res.file, res.filename);
    })
    .finally(() => {
      exportLoading.value = false;
    });
};

const getDataList = async (_params) => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value - 1,
      size: pageSize.value,
      billCode: _params?.billCode,
      status: _params?.status,
      createdTimeStart: _params?.date?.[0]
        ? moment(_params?.date?.[0]).format("YYYY-MM-DD HH:mm:ss")
        : undefined,
      createdTimeEnd: _params?.date?.[1]
        ? moment(_params?.date?.[1]).format("YYYY-MM-DD HH:mm:ss")
        : undefined,
      ["tenantName" + locale.value]: _params?.tenantName,
    };

    const res = await Api.tenantSettlementList(params);
    tableData.value = res.data?.content || [];
    total.value = Number(res.data?.totalElements || 0);
  } catch (error) {
    console.error("获取结算账单列表失败", error);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  getDataList();
});
</script>

<style lang="scss" scoped>
.color-555555 {
  color: #555555;
}

.addBtn {
  height: 28px;
  margin-left: 10px;
  padding: 0 7px;
  border-radius: 3px;
  background: #fff;
  cursor: pointer;
}
</style>
